import 'dart:convert';

import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../../models/invoice_entity.dart';
import '../../../models/pay_order_list_entity.dart';
import '../../../remote/request.dart';
import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';

class OrderPaidDetailLogic extends GetxController {
  var orderDetail = Rxn<PaidOrderInfo>();

  final apiService = Get.find<ApiService>();

  final paymentInfo = <String, String>{}.obs;
  final orderInfo = <String, String>{}.obs;

  final invoiceDetail = Rxn<InvoiceEntity>();
  final caseList = <InvoiceRelateCases>[].obs;

  @override
  void onInit() {
    super.onInit();
    orderDetail.value = Get.arguments;
    invoiceDetail.value =
        InvoiceEntity.fromJson(jsonDecode(orderDetail.value!.invoice ?? ''));

    paymentInfo['户名'] = orderDetail.value!.title!.split(',')[0];
    paymentInfo['卡号'] = orderDetail.value!.title!.split(',')[1];
    paymentInfo['开户行'] = orderDetail.value!.title!.split(',')[2];

    orderInfo['创建人'] = orderDetail.value!.creatorName ?? '';
    orderInfo['手机号'] = orderDetail.value!.mobile ?? '';
    orderInfo['创建时间'] = DateFormat('yyyy.MM.dd HH:mm').format(
        DateTime.fromMillisecondsSinceEpoch(orderDetail.value!.createdAt!));
    orderInfo['更新时间'] = DateFormat('yyyy.MM.dd HH:mm').format(
        DateTime.fromMillisecondsSinceEpoch(orderDetail.value!.updatedAt!));
    orderInfo['订单号'] = orderDetail.value!.id ?? '';
    orderInfo['备注'] = orderDetail.value!.orderRemark ?? '';

    caseList.value = invoiceDetail.value!.relateCases ?? [];
  }

  void onClickCase(int index) {
    Get.toNamed(RouteGet.caseDetail, arguments: caseList[index].caseId);
  }

  void cancelOrder() => request(
        () async {
          var result = await apiService.deleteOrder(orderDetail.value!.id!);

          if (result != null) {
            Get.back(result: true);
          }
        },
        showLoading: true,
        message: '取消中...',
      );
}
